import { query } from '../../config/db.js';

/**
 * 宠物数据模型
 */
export class Pet {
  constructor(petData) {
    this.id = petData.id;
    this.user_id = petData.user_id;
    this.name = petData.name;
    this.species = petData.species;
    this.breed = petData.breed;
    this.color = petData.color;
    this.gender = petData.gender;
    this.age = petData.age;
    this.description = petData.description;
    this.photo_url = petData.photo_url;
    this.created_at = petData.created_at;
  }

  /**
   * 创建新宠物
   * @param {Object} petData - 宠物数据
   * @returns {Promise<Object>} 创建的宠物信息
   */
  static async create(petData) {
    const { 
      user_id, 
      name, 
      species, 
      breed, 
      color, 
      gender, 
      age, 
      description, 
      photo_url 
    } = petData;
    
    const sql = `
      INSERT INTO pets (user_id, name, species, breed, color, gender, age, description, photo_url)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    try {
      const result = await query(sql, [
        user_id, 
        name || null, 
        species, 
        breed || null, 
        color, 
        gender, 
        age || null, 
        description || null, 
        photo_url || null
      ]);
      
      // 返回新创建的宠物信息
      const newPet = await Pet.findById(result.insertId);
      return newPet;
    } catch (error) {
      console.error('创建宠物失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找宠物
   * @param {number} id - 宠物ID
   * @returns {Promise<Object|null>} 宠物信息或null
   */
  static async findById(id) {
    const sql = `
      SELECT p.*, u.username as owner_name
      FROM pets p
      LEFT JOIN users u ON p.user_id = u.id
      WHERE p.id = ?
    `;
    
    try {
      const results = await query(sql, [id]);
      return results.length > 0 ? new Pet(results[0]) : null;
    } catch (error) {
      console.error('查找宠物失败:', error);
      throw error;
    }
  }

  /**
   * 根据用户ID查找宠物列表
   * @param {number} userId - 用户ID
   * @param {Object} options - 查询选项
   * @returns {Promise<Array>} 宠物列表
   */
  static async findByUserId(userId, options = {}) {
    const { page = 1, limit = 10 } = options;
    const offset = (page - 1) * limit;
    
    const sql = `
      SELECT * FROM pets
      WHERE user_id = ?
      ORDER BY created_at DESC
      LIMIT ${parseInt(limit)} OFFSET ${parseInt(offset)}
    `;

    try {
      const results = await query(sql, [userId]);
      return results.map(pet => new Pet(pet));
    } catch (error) {
      console.error('查找用户宠物失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户宠物总数
   * @param {number} userId - 用户ID
   * @returns {Promise<number>} 宠物总数
   */
  static async countByUserId(userId) {
    const sql = 'SELECT COUNT(*) as count FROM pets WHERE user_id = ?';
    
    try {
      const results = await query(sql, [userId]);
      return results[0].count;
    } catch (error) {
      console.error('获取用户宠物总数失败:', error);
      throw error;
    }
  }

  /**
   * 搜索宠物
   * @param {Object} searchParams - 搜索参数
   * @param {Object} options - 查询选项
   * @returns {Promise<Array>} 宠物列表
   */
  static async search(searchParams = {}, options = {}) {
    const { species, breed, color, gender } = searchParams;
    const { page = 1, limit = 10 } = options;
    const offset = (page - 1) * limit;
    
    let sql = `
      SELECT p.*, u.username as owner_name
      FROM pets p
      LEFT JOIN users u ON p.user_id = u.id
      WHERE 1=1
    `;
    const params = [];

    if (species) {
      sql += ' AND p.species LIKE ?';
      params.push(`%${species}%`);
    }

    if (breed) {
      sql += ' AND p.breed LIKE ?';
      params.push(`%${breed}%`);
    }

    if (color) {
      sql += ' AND p.color LIKE ?';
      params.push(`%${color}%`);
    }

    if (gender) {
      sql += ' AND p.gender = ?';
      params.push(gender);
    }

    sql += ' ORDER BY p.created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));

    try {
      const results = await query(sql, params);
      return results.map(pet => new Pet(pet));
    } catch (error) {
      console.error('搜索宠物失败:', error);
      throw error;
    }
  }

  /**
   * 获取搜索结果总数
   * @param {Object} searchParams - 搜索参数
   * @returns {Promise<number>} 总数
   */
  static async countSearch(searchParams = {}) {
    const { species, breed, color, gender } = searchParams;
    
    let sql = 'SELECT COUNT(*) as count FROM pets WHERE 1=1';
    const params = [];

    if (species) {
      sql += ' AND species LIKE ?';
      params.push(`%${species}%`);
    }

    if (breed) {
      sql += ' AND breed LIKE ?';
      params.push(`%${breed}%`);
    }

    if (color) {
      sql += ' AND color LIKE ?';
      params.push(`%${color}%`);
    }

    if (gender) {
      sql += ' AND gender = ?';
      params.push(gender);
    }

    try {
      const results = await query(sql, params);
      return results[0].count;
    } catch (error) {
      console.error('获取搜索结果总数失败:', error);
      throw error;
    }
  }

  /**
   * 更新宠物信息
   * @param {number} id - 宠物ID
   * @param {Object} updateData - 要更新的数据
   * @returns {Promise<Object|null>} 更新后的宠物信息
   */
  static async update(id, updateData) {
    const allowedFields = ['name', 'species', 'breed', 'color', 'gender', 'age', 'description', 'photo_url'];
    const updateFields = [];
    const updateValues = [];

    // 只允许更新指定字段
    for (const field of allowedFields) {
      if (updateData[field] !== undefined) {
        updateFields.push(`${field} = ?`);
        updateValues.push(updateData[field]);
      }
    }

    if (updateFields.length === 0) {
      throw new Error('没有可更新的字段');
    }

    updateValues.push(id);
    const sql = `
      UPDATE pets 
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    try {
      await query(sql, updateValues);
      return await Pet.findById(id);
    } catch (error) {
      console.error('更新宠物失败:', error);
      throw error;
    }
  }

  /**
   * 删除宠物
   * @param {number} id - 宠物ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async delete(id) {
    const sql = 'DELETE FROM pets WHERE id = ?';
    
    try {
      const result = await query(sql, [id]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除宠物失败:', error);
      throw error;
    }
  }

  /**
   * 检查宠物是否属于指定用户
   * @param {number} petId - 宠物ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} 是否属于该用户
   */
  static async belongsToUser(petId, userId) {
    const sql = 'SELECT COUNT(*) as count FROM pets WHERE id = ? AND user_id = ?';
    
    try {
      const results = await query(sql, [petId, userId]);
      return results[0].count > 0;
    } catch (error) {
      console.error('检查宠物所有权失败:', error);
      throw error;
    }
  }

  /**
   * 获取宠物统计信息
   * @returns {Promise<Object>} 统计信息
   */
  static async getStats() {
    const sql = `
      SELECT 
        COUNT(*) as total_pets,
        COUNT(CASE WHEN species = '狗' THEN 1 END) as dogs,
        COUNT(CASE WHEN species = '猫' THEN 1 END) as cats,
        COUNT(CASE WHEN gender = 'male' THEN 1 END) as males,
        COUNT(CASE WHEN gender = 'female' THEN 1 END) as females,
        COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today_added
      FROM pets
    `;

    try {
      const results = await query(sql);
      return results[0];
    } catch (error) {
      console.error('获取宠物统计失败:', error);
      throw error;
    }
  }

  /**
   * 转换为JSON格式
   * @returns {Object} 宠物信息
   */
  toJSON() {
    return {
      id: this.id,
      user_id: this.user_id,
      name: this.name,
      species: this.species,
      breed: this.breed,
      color: this.color,
      gender: this.gender,
      age: this.age,
      description: this.description,
      photo_url: this.photo_url,
      created_at: this.created_at,
      owner_name: this.owner_name
    };
  }
}
